package com.jfinal.weixin.controller;

import com.jfinal.core.Controller;
import com.jfinal.kit.StrKit;
import com.jfinal.weixin.model.RedPackLog;
import com.jfinal.weixin.model.WeixinInfo;
import com.jfinal.weixin.sdk.api.RedPackApi;
import com.jfinal.weixin.sdk.kit.PaymentKit;
import java.util.HashMap;
import java.util.Map;

public class RedPackApiController extends Controller {
	private  String sendName = "红安人独享福利";
	WeixinInfo weixinInfo = WeixinInfo.dao.findById(1);
	private  String wxappid = weixinInfo.getStr("appid");
	private  String partner = weixinInfo.getInt("partner")+"";
	private  String paternerKey = weixinInfo.getStr("paternerKey");
	private  String certPath = weixinInfo.getStr("certPath");
	private  String ip = weixinInfo.getStr("serverip");
	public String send(String openid,String activityName,String add) {
		String reopenid = openid;
		String mchBillno = System.currentTimeMillis() + "";
		Map<String, String> params = new HashMap<String, String>();
		params.put("nonce_str", System.currentTimeMillis() / 1000 + "");
		params.put("mch_billno", mchBillno);
		params.put("mch_id", partner);
		params.put("wxappid", wxappid);
		params.put("send_name", sendName);
		params.put("re_openid", reopenid);
		System.out.println("<><><><>"+reopenid+"<><><><>");
		params.put("total_amount", "100");
		params.put("total_num", "1");
		params.put("wishing", "红安人专属福利");
		params.put("client_ip", ip);
		params.put("act_name", activityName);
		params.put("remark", add);
		String sign = PaymentKit.createSign(params, paternerKey);
		params.put("sign", sign);
		String xmlResult = RedPackApi.sendRedPack(params, certPath, partner);
		Map<String, String> result = PaymentKit.xmlToMap(xmlResult);
		String result_code = result.get("result_code");
		String return_code = result.get("return_code");
		String mch_billno = result.get("mch_billno");
		String sendResult="";
		if (StrKit.isBlank(result_code) || !"SUCCESS".equals(result_code)) {
			System.out.println(result.toString());
			sendResult = "发送失败";
		} else {
			sendResult = "发送成功";
			RedPackLog redPackLog = new RedPackLog();
			redPackLog.set("openid",openid);
			redPackLog.set("result_code",result_code);
			redPackLog.set("mch_billno",mch_billno);
			redPackLog.save();
		}
		return sendResult;
	}

	public Map query(String billno) {
		Map<String, String> params = new HashMap<String, String>();
		params.put("nonce_str", System.currentTimeMillis() / 1000 + "");
		params.put("mch_billno", billno);
		params.put("mch_id", partner);
		params.put("appid", wxappid);
		params.put("bill_type", "MCHT");
		String sign = PaymentKit.createSign(params, paternerKey);
		params.put("sign", sign);
		String xmlResult = RedPackApi.getHbInfo(params, certPath, partner);
		Map<String, String> result = PaymentKit.xmlToMap(xmlResult);
		return result;
	}

}